package gecko.mqtt;

/**
 * @author 陈永佳 (yoojiachen@gmail.com)
 * @version 0.0.1
 */
class MqttTopic {

    public static final String EVENT_TYPE_REQS = "requests";
    public static final String EVENT_TYPE_REPS = "replies";

    // / gecko / {nodeId} @ {domain} / {eventType} / {groupAddr} / {physicalAddr} / {eventId}

    public final String nodeId;
    public final String domain;
    public final String eventType;
    public final String groupAddress;
    public final String physicalAddress;
    public final long eventId;

    MqttTopic(String nodeId, String domain, String eventType, String groupAddress, String physicalAddress, long eventId) {
        this.nodeId = nodeId;
        this.domain = domain;
        this.eventType = eventType;
        this.groupAddress = groupAddress;
        this.physicalAddress = physicalAddress;
        this.eventId = eventId;
    }

    public static MqttTopic parse(String topic) throws Exception {
        final String[] topicSeg = topic.split("/");
        if (topicSeg.length < 6) {
            throw new IllegalArgumentException("Topic格式错误: " + topic);
        }
        final String nodeIdDomain = topicSeg[1];
        final String[] nd = nodeIdDomain.split("@");
        if (nd.length != 2) {
            throw new IllegalArgumentException("Topic.NodeId & Domain格式错误: " + nodeIdDomain);
        }
        final String eventType = topicSeg[2];
        final String groupAddr = topicSeg[3];
        final String physicalAddr = topicSeg[4];
        final String eventId = topicSeg[5];
        return new MqttTopic(
                nd[1],
                nd[0],
                eventType,
                groupAddr,
                physicalAddr,
                Long.parseLong(eventId)
        );
    }
}
